﻿namespace Reviewer.Web.UI
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using Reviewer.Entities;
    using System.Reflection;
    using Reviewer.Entities.MetadataInfo;
    using System.Runtime.Serialization;
    using Reviewer.Entities.Services;
    using System.Collections;
    using Reviewer.Business.Services;
    using System.ComponentModel;
    using System.Configuration;
    using System.Drawing.Imaging;
    using System.IO;
    using Reviewer.Business;

    public class MetadataDropDownPropertyControl : MetadataPropertyControl
    {
        protected DropDownList list = new DropDownList();
        public MetadataDropDownPropertyControl(PropertyInfo property)
            : base(property)
        {
            this.Load += new EventHandler(MetadataDropDownPropertyControl_Load);
        }

        void MetadataDropDownPropertyControl_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                this.EnsureChildControls();

                MetadataLookupPropertyAttribute attribute = Attribute.GetCustomAttribute(this.propertyInfo, typeof(MetadataLookupPropertyAttribute)) as MetadataLookupPropertyAttribute;

                MetadataTypeAttribute lookupTypeAttribute = Attribute.GetCustomAttribute(attribute.LookupMetadataType, typeof(MetadataTypeAttribute)) as MetadataTypeAttribute;

                Type serviceType = typeof(MetadataService<>).MakeGenericType(attribute.LookupMetadataType);
                object service = Activator.CreateInstance(serviceType);

                IEnumerable listData = serviceType.InvokeMember("GetAll", BindingFlags.InvokeMethod, null, service, null) as IEnumerable;
                this.list.DataSource = listData;
                this.list.DataTextField = "Name";
                this.list.DataValueField = "Id";
                this.list.DataBind();
            }
        }

        protected override void CreateChildControlsEx()
        {
            this.list.ID = this.ID + "_Ddl" + this.propertyInfo.Name;
            this.list.ValidationGroup = this.ValidationGroup;

            this.Controls.Add(this.list);

            this.label.AssociatedControlID = this.list.ID;
        }

        public override void Reset()
        {
            EnsureChildControls();

            this.list.SelectedIndex = -1;
        }

        public override void SetProperty(object item)
        {
            this.EnsureChildControls();

            this.propertyInfo.SetValue(item, Convert.ToInt32(this.list.SelectedValue), null);
        }

        public override void GetProperty(object item)
        {
            this.EnsureChildControls();

            this.list.SelectedValue = this.propertyInfo.GetValue(item, null).ToString();
        }
    }
}